﻿/*
    a05_Nullable @ https://gitee.com/zcatt/MyDemo2020

形如T?的类型对应了Nullable<T>, 其支持null值. 其应当视作struct.

T应当是值类型(value type).实际上ref type天然就是nullable的,不需多此一举.

Nullable<T>的两个重要properties: HasValue和Value. 当null时, 访问Value会触发InvalidOperationException.

 */ 
using System;

public class IntData
{
    public int num;
}

class Program
{
    static void Main(string[] args)
    {
        int? n = 1;

        //k与n已经是不同struct
        int? k = n;
        k = 10;
        Console.WriteLine("n={0}, k = {1}", n, k);

        showNullable(ref n);
        Console.WriteLine("n = " + n);


        //null情形
        int? m = null;
        showNullable(ref m);
        Console.WriteLine("m = " + m);

        return;
    }

    static void showNullable(ref int? num)
    {
        if(num.HasValue)
        {
            Console.WriteLine("num = " + num);
        }
        else
        {
            Console.WriteLine("num = null");
        }

        try
        {
            Console.WriteLine("num = {0}", num.Value);
        }
        catch (InvalidOperationException e)
        {
            Console.WriteLine(e.Message);
        }

        num = 4;
    }

}
